package setup

import (
	"context"
	"fmt"
	"gitee.com/alex_li/upload/internal/etc"
	"github.com/lishimeng/go-log"
	"os"
	"path/filepath"
	"time"
)

const (
	interval = time.Hour
	duration = time.Minute*60*24
)

func clearFleJob(ctx context.Context) (err error) {
	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			case <-time.After(interval):
				clearExpiredFile()
			}
		}
	}()
	return
}

func clearExpiredFile() {
	log.Info("remove expired files...")
	if !etc.Config.AuthClear.Enable {
		log.Info("component autoClear is disabled")
		return
	}
	rootPath := etc.Config.Upload.Root
	fmt.Printf(rootPath)
	_ = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {

		if err != nil {
			return err
		}
		if path == rootPath {
			return nil
		}
		log.Info("check file:%s", path)
		if info.ModTime().Add(duration).After(time.Now()) {
			log.Info("remove tmp file[%s]", path)
			e := os.Remove(path)
			if e != nil {
				log.Info("unable to remove %s", path)
				log.Info(err)
			}
		}
		return nil
	})
}